<template>
  <el-card class="mb-20">
    <template #header>
      <div class="card-header">
        <div class="header-title">
          <span>任务目源关系配置</span>
          <el-tooltip content="配置目标字段与源数据之间的映射关系" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
        <el-button type="primary" size="small" @click="handleAddMapping" :disabled="!hasTargetColumns">
          <el-icon><Plus /></el-icon>添加映射关系
        </el-button>
      </div>
    </template>
    
    <div v-if="!hasTargetColumns" class="empty-tip">
      <el-empty description="尚未配置目标列">
        <template #image>
          <el-icon class="empty-icon"><Connection /></el-icon>
        </template>
        <template #description>
          <div>
            <p>尚未配置目标列</p>
            <p class="small-tip">请先在"任务目标配置"中添加至少一个列</p>
          </div>
        </template>
      </el-empty>
    </div>
    
    <div v-else-if="!form.ts_mapping || form.ts_mapping.length === 0" class="empty-tip">
      <el-empty description="暂无目源关系映射">
        <template #image>
          <el-icon class="empty-icon"><Connection /></el-icon>
        </template>
        <template #description>
          <div>
            <p>暂无目源关系映射</p>
            <p class="small-tip">点击"添加映射关系"按钮来配置数据源映射</p>
          </div>
        </template>
        <el-button type="primary" @click="handleAddMapping">添加映射关系</el-button>
      </el-empty>
    </div>
    
    <div v-else>
      <el-alert
        title="目源关系映射说明"
        type="info"
        :closable="false"
        show-icon
        class="alert-tip"
      >
        为每个目标列配置对应的源数据来源，包括源数据库、表和列。可为同一目标列配置多个不同优先级的数据源。
      </el-alert>
      
      <el-table 
        ref="tableRef" 
        :data="form.ts_mapping" 
        style="width: 100%" 
        border
        :height="tableHeight"
        highlight-current-row
        class="mapping-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        
        <!-- 目标列 -->
        <el-table-column label="目标列名" prop="target_column_name" width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.target_column_name" 
              placeholder="请选择目标列名"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="detail in form.details"
                :key="detail.column_name"
                :label="detail.column_name"
                :value="detail.column_name"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="选择需要映射的目标表字段" placement="top">
              <span>目标列名<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 来源数据源 -->
        <el-table-column label="来源数据源" prop="db_info_setting_id" width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.db_info_setting_id" 
              placeholder="请选择来源数据源"
              style="width: 100%"
              filterable
              @change="(val) => handleSourceDataSourceChange(val, row)"
            >
              <el-option
                v-for="item in dataSourceOptions"
                :key="item._id"
                :label="item.connection_name"
                :value="item._id"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="选择数据来源的数据库连接" placement="top">
              <span>来源数据源<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 来源表名 -->
        <el-table-column label="来源表名" prop="source_table_name" width="140">
          <template #default="{ row }">
            <el-select
              v-model="row.source_table_name"
              placeholder="请选择来源表名"
              style="width: 100%"
              filterable
              :disabled="!row.db_info_setting_id"
              @change="(val) => handleSourceTableChange(val, row)"
            >
              <el-option
                v-for="table in getSourceTables(row)"
                :key="table"
                :label="table"
                :value="table"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="选择数据来源的表名" placement="top">
              <span>来源表名<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 来源列名 -->
        <el-table-column label="来源列名" prop="source_column_name" width="140">
          <template #default="{ row }">
            <el-select 
              v-model="row.source_column_name" 
              placeholder="请选择来源列名"
              style="width: 100%"
              filterable
              :disabled="!canSelectSourceColumn(row)"
            >
              <el-option
                v-for="column in getSourceColumns(row)"
                :key="column"
                :label="column"
                :value="column"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="选择数据来源的列名" placement="top">
              <span>来源列名<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 条件 -->
        <el-table-column label="条件" prop="condition" min-width="120">
          <template #default="{ row }">
            <el-input 
              v-model="row.condition" 
              placeholder="请输入查询条件，如: id > 100" 
              clearable 
            />
          </template>
          <template #header>
            <el-tooltip content="用于筛选源数据的WHERE条件" placement="top">
              <span>条件<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 优先级 -->
        <el-table-column label="优先级" prop="priority" width="110" align="center">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.priority" 
              :min="1" 
              :step="1" 
              controls-position="right"
              style="width: 80px;"
            />
          </template>
          <template #header>
            <el-tooltip content="当有多个数据源时，优先使用较小数值的数据源" placement="top">
              <span>优先级<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 目标查询列名 -->
        <el-table-column label="目标查询列名" prop="target_query_column" width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.target_query_column" 
              placeholder="请选择"
              style="width: 100%"
              filterable
              clearable
            >
              <el-option
                v-for="detail in form.details"
                :key="detail.column_name"
                :label="detail.column_name"
                :value="detail.column_name"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="目标表用于查询的列名" placement="top">
              <span>目标查询列<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 源表查询列名 -->
        <el-table-column label="源表查询列名" prop="source_query_column" width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.source_query_column" 
              placeholder="请选择"
              style="width: 100%"
              filterable
              clearable
              :disabled="!canSelectSourceColumn(row)"
            >
              <el-option
                v-for="column in getSourceColumns(row)"
                :key="column"
                :label="column"
                :value="column"
              />
            </el-select>
          </template>
          <template #header>
            <el-tooltip content="源表用于查询的列名" placement="top">
              <span>源表查询列<el-icon class="help-icon"><QuestionFilled /></el-icon></span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <!-- 操作 -->
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              circle
              @click="handleDeleteMapping($index)"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-button type="primary" size="small" plain @click="handleAddMapping">
          <el-icon><Plus /></el-icon>继续添加
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref, onMounted, nextTick, computed, watch } from 'vue';
import { Delete, Plus, Connection, QuestionFilled } from '@element-plus/icons-vue';
import { fetchTables } from '../form-utils';

// 定义props
const props = defineProps({
  form: {
    type: Object,
    required: true
  },
  dataSourceOptions: {
    type: Array,
    default: () => []
  },
  sourceTableColumns: {
    type: Object,
    default: () => ({})
  }
});

// 定义事件
const emit = defineEmits(['fetch-source-columns']);

// 源表选项缓存 (db_id -> tables[])
const sourceTableOptions = ref<Record<string, string[]>>({});

// 表格引用
const tableRef = ref(null);
const tableHeight = ref("auto");

// 计算属性：是否有目标列
const hasTargetColumns = computed(() => 
  props.form.details && props.form.details.length > 0 &&
  props.form.details.some(item => item.column_name)
);

// 是否可以选择源列
const canSelectSourceColumn = (row: any) => {
  return !!row.db_info_setting_id && !!row.source_table_name;
};

// 添加映射关系
const handleAddMapping = () => {
  if (!props.form.ts_mapping) {
    props.form.ts_mapping = [];
  }
  
  props.form.ts_mapping.push({
    target_column_name: '',
    db_info_setting_id: '',
    source_table_name: '',
    source_column_name: '',
    condition: '',
    priority: 1,
    target_query_column: '',
    source_query_column: ''
  });
  
  // 添加数据后刷新表格
  nextTick(() => {
    refreshTableLayout();
  });
};

// 删除映射关系
const handleDeleteMapping = (index: number) => {
  props.form.ts_mapping.splice(index, 1);
  
  // 删除数据后刷新表格
  nextTick(() => {
    refreshTableLayout();
  });
};

// 表格布局刷新函数
const refreshTableLayout = () => {
  if (tableRef.value) {
    // @ts-ignore
    tableRef.value.doLayout();
    
    // 触发窗口 resize 事件，让表格重新计算布局
    window.dispatchEvent(new Event('resize'));
  }
};

// 来源数据源变更事件
const handleSourceDataSourceChange = async (dbId: string, row: any) => {
  // 清空表名和列名
  row.source_table_name = '';
  row.source_column_name = '';
  row.source_query_column = '';
  
  // 如果有数据源ID，获取表列表
  if (dbId) {
    if (!sourceTableOptions.value[dbId]) {
      const tables = await fetchTables(dbId);
      sourceTableOptions.value[dbId] = tables;
    }
  }
};

// 获取来源表名选项
const getSourceTables = (row: any) => {
  if (!row.db_info_setting_id) {
    return [];
  }
  
  return sourceTableOptions.value[row.db_info_setting_id] || [];
};

// 来源表名变更事件
const handleSourceTableChange = (val: string, row: any) => {
  // 清空列名和源表查询列名
  row.source_column_name = '';
  row.source_query_column = '';
  
  // 获取列名
  if (row.db_info_setting_id && val) {
    emit('fetch-source-columns', row.db_info_setting_id, val);
  }
};

// 获取来源列名选项
const getSourceColumns = (row: any) => {
  if (!row.db_info_setting_id || !row.source_table_name) {
    return [];
  }
  
  const key = `${row.db_info_setting_id}:${row.source_table_name}`;
  return props.sourceTableColumns[key] || [];
};

// 监听数据变化
watch(
  () => [props.form.ts_mapping?.length, props.form.details?.length],
  () => {
    nextTick(() => {
      refreshTableLayout();
    });
  }
);

// 组件挂载后确保表格布局正确
onMounted(() => {
  // 确保表格在DOM完全渲染后重新布局
  setTimeout(() => {
    refreshTableLayout();
  }, 300);
});
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
}

.help-icon {
  margin-left: 4px;
  font-size: 14px;
  color: #909399;
}

.empty-tip {
  padding: 20px 0;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
}

.small-tip {
  font-size: 12px;
  color: #909399;
}

.alert-tip {
  margin-bottom: 15px;
  font-size: 13px;
}

.table-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.mapping-table :deep(th) {
  display: table-cell !important;
}

.mapping-table :deep(thead) {
  display: table-header-group !important;
}

.mapping-table :deep(.el-table__header) {
  display: table !important;
}
</style>